<template>
    <div class="takeOrder">
        <div class="search-product-box" :class="{fliter:(showCarDetail||showPayBox||showCode||showDelConfirm||isqrcode)}">
            <div class="search-produc">
                <i class="iconfont icon-sousuo"></i>
                <input type="text" placeholder="请输入要检索的商品名" v-model="product">
            </div>
            <div class="product-box" v-if="productList.length>0" @click.stop="productList=[];product=''">
                <ul class="ul">
                    <li class="product-item" v-for="item in productList" @click.stop="shoiceProduct(item)">
                        <span v-text="item.name"></span>
                    </li>
                </ul>
            </div>
        </div>
        <div style="height:1rem;"></div>
        <!-- 商品列表 -->
        <div class="goodsBox clearfix">
            <div class="left_bar left" id="left_bar">
                <div id="left_bar_scroll">
                    <div v-if="goodsData[0].typeName" class="item flex flex-align-center flex-pack-center" v-for="(oitem,index) in goodsData" v-text="oitem.typeName" :class="{active:curIdx==index}" @click="changeGoodType(index)"></div>
                </div>
            </div>
            <div class="right_goods left" id="right_goods">
                <div id="right_goods_scroller">
                    <div class="goods_item oneLevel">
                        <div class="goods_li" v-for="(item,ind) in goodsData[curIdx].products" v-if="item.productStatus!='OFF'">
                            <div class="goodImg left" :class="{'goodImg-border':!item.imageURl}" @click="showImg(item.imageURl)">
                                <!-- <img :src="item.imageURl+'?x-oss-process=image/resize,l_300'" alt=""> -->
                                <img v-lazy="item.imageURl+'?x-oss-process=image/resize,l_300'" alt=""/>
                            </div>
                            <div class="goodMsg" @click="beforeSelGoods(item)">
                                <p class="name" v-text="item.name"></p>
		                        <p class="desc" v-text="item.note" v-if="item.note!=null"></p>
                                <div class="msgBottom clearfix" :class="item.note!=null?'has-note':''">
                                    <div class="price left" v-text=" '￥' + item.salesPrice"></div>
                                    <div class="changeNumber right clearfix" v-if="(item.stockEnabled&&!item.quantity)">
                                        <span class="addNumber left" style="font-size: .28rem;">无货</span>
                                    </div>
                                    <div class="changeNumber right clearfix" v-else>
                                        <span v-if="item.id!=='0'" class="addNumber left" :id="item.id"><i class="iconfont icon-tianjia1"></i></span>
                                    </div>
                                    <div class="addMore right" v-if="item.id=='0'" @click.stop="openNumberBox(item.id)">自定义网费</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="goods_item" v-for="(item,ind) in goodsData[curIdx].subTypes" @click="traggerType($event)" v-if="item.productStatus!='OFF'">
                        <p class="title_name" v-text="item.typeName"></p>
                        <div class="goods_li" v-for="(item,ind) in item.products">
                            <div class="goodImg left" :class="{'goodImg-border':!item.imageURl}" @click.stop="showImg(item.imageURl)">
                                <img v-lazy="item.imageURl+'?x-oss-process=image/resize,l_300'" alt="">
                            </div>
                            <div class="goodMsg"  @click.stop="beforeSelGoods(item);">
                                <p class="name" v-text="item.name"></p>
		                        <p class="desc" v-text="item.note" v-if="item.note!=null"></p>
                                <div class="msgBottom clearfix" :class="item.note!=null?'has-note':''">
                                    <div class="price left" v-text=" '￥' + item.salesPrice"></div>
                                    <div class="changeNumber right clearfix" v-if="(item.stockEnabled&&!item.quantity)">
                                        <span class="addNumber left" style="font-size: .28rem;">无货</span>
                                    </div>
                                    <div class="changeNumber right clearfix" v-else>
                                        <span class="addNumber left" :id="item.id"><i class="iconfont icon-tianjia1"></i></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 购物车 -->
        <div class="shopCar clearfix">
            <div class="carImgBox left flex flex-align-center flex-pack-center" @click="choiceArr.length>0?showCarDetail=true:null">
                <div class="carImg">
                    <div class="goodsNumber flex flex-align-center flex-pack-center" v-text="totalPrice.count"></div>
                    <i class="iconfont icon-gouwuchekong"></i>
                </div>
            </div>
            <div class="totalPrice left" v-text="'￥'+totalPrice.amount.toFixed(2)"></div>
            <!-- <button type="button" @click="delOrder">删除订单</button> -->
            <button type="button" class="confirmBtn right" @click="goPayType">选好了</button>
        </div>

        <!-- 购物车详情 -->
        <!-- <div class="carDetailBox" :style="{display:(showCarDetail?'block':'none')}" @click="showCarDetail=false">
            <div class="carDetail" @click.stop="">
                <div class="goodsBox" id="carGoodsBox" :style="{height:(0.88*(choiceArr.length-1)+0.44)+'rem'}">
                    <div id="carGoodsBox_scroll">
                        <div class="goodItem clearfix" v-for="item in choiceArr">
                            <div class="name left" v-text="item.productName"></div>
                            <div class="price left" v-text="'￥'+item.dealPrice"></div>
                            <div class="changeNumber right">
                                <span class="reduceNumber" @click="reduceProduct(item.productId)"><i class="iconfont icon-jianshao1"></i></span>
                                <span class="number" v-text="item.quantity"></span>
                                <span class="addNumber" @click="addProduct(item.productId, false)"><i class="iconfont icon-tianjia1"></i></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div> -->
        <div class="carDetailBox" :style="{display:(showCarDetail?'block':'none')}" @click="showCarDetail=false">
			<div class="carDetail" @click.stop="">
				<!-- <div class="goodsBox" id="carGoodsBox" :style="{height:(0.88*(choiceArr.length-1)+0.44)+'rem'}"> -->
				<div class="goodsBox" id="carGoodsBox">
					<div id="carGoodsBox_scroll">
						<div class="goodItem clearfix" v-for="item in choiceArr">
							<div class="name left">
                                <div class="g-name">{{item.productName}}</div>
                                <div class="add-pei" v-if="item.matchEnabled">
                                    <span class="btn" @click="doShowPeiGoods(item)">添加配品</span>
                                </div>
                            </div>
							<div class="price left" v-text="'￥'+(item.salesPrice/item.quantity).toFixed(2)"></div>
							<div class="changeNumber right">
								<span class="reduceNumber" @click="reduceProduct(item.productId,item)"><i class="iconfont icon-jianshao1"></i></span>
								<span class="number" v-text="item.quantity"></span>
								<span class="addNumber" @click="addProduct(item.productId, false,null,item)"><i class="iconfont icon-tianjia1"></i></span>
							</div>
                            <div class="sub-items" v-if="item.masterItemDtos && Array.isArray(item.masterItemDtos) && item.masterItemDtos.length">
                                <div class="goodItem clearfix" v-for="it in item.masterItemDtos">
                                    <div class="name left">
                                        <div class="g-name"><span class="btn">配</span>{{it.productName}}</div>
                                        <!-- <div class="add-pei"> -->
                                        <!-- </div> -->
                                    </div>
                                    <div class="price left" v-text="'￥'+(it.salesPrice/it.quantity).toFixed(2)"></div>
                                    <div class="changeNumber right">
                                        <span class="reduceNumber" @click="reduceAmountForPei(it)"><i class="iconfont icon-jianshao1"></i></span>
                                        <span class="number" v-text="it.quantity"></span>
                                        <span class="addNumber" @click="addAmountForPei(item,it)"><i class="iconfont icon-tianjia1"></i></span>
                                    </div>
                                </div>
                            </div>
                            <!-- 规格 -->
                            <div class="spec-info" v-if="item.specs && Array.isArray(item.specs) && item.specs.length">
                                <!-- 规格：<span class="tag" v-for="(it,ind) in item.specs" :key="ind">{{it}}</span> -->
                                规格：<span class="tag" :key="ind">{{item.specs.join("、")}}</span>
                            </div>
                            <!-- 规格end -->
						</div>
					</div>
				</div>
			</div>
		</div>

        <div class="numberMaskBox" v-if="showNumBox" @click="showNumBox=false">
            <div class="numberMask" id="numberMask" @click.stop="">
                <div class="inputBox" v-text="goodNumber"></div>
                <div class="numberBox clearfix">
                    <div class="number" @click="clickNum('1')">1</div>
                    <div class="number" @click="clickNum('2')">2</div>
                    <div class="number" @click="clickNum('3')">3</div>
                    <div class="number" @click="clickNum('4')">4</div>
                    <div class="number" @click="clickNum('5')">5</div>
                    <div class="number" @click="clickNum('6')">6</div>
                    <div class="number" @click="clickNum('7')">7</div>
                    <div class="number" @click="clickNum('8')">8</div>
                    <div class="number" @click="clickNum('9')">9</div>
                    <div class="number" @click="delNumber()">删除</div>
                    <div class="number" @click="clickNum('0')">0</div>
                    <div class="number" @click="saveNumber()">保存</div>
                </div>
            </div>
        </div>
        <div class="goodAnimate"></div>
        <div id="show-img-info" v-if="nowImg===''?false:true" @click.stop="hideImg">
            <img :src="nowImg" alt="" @click.stop="">
            <span class="close" @click="hideImg">关闭</span>
        </div>
        <div class="pei-goods-wrap" v-if="showPeiGoods" @click="showPeiGoods = false">
            <div class="inner-wrap" @click.stop="">
                <div class="pei-goods">
                    <div class="item" v-for="(it,ind) in peiGoods" :class="{active:nowSelPeiGoodsIds.indexOf(it.id)!=-1}" @click="modifyPeiGoods('add',it)" :key="ind">
                        <div class="info">
                            <div class="item-name">{{it.name}}</div>
                            <div class="item-price">¥{{it.salesPrice}}</div>
                        </div>
                    </div>
                </div>
                <span class="sure" @click.stop="submitSelPei">确认</span>
            </div>
        </div>
        <!-- 规格 -->
        <div class="pei-goods-wrap spec-wrap" v-if="showSelSpec" @click="showSelSpec = false">
            <div class="inner-wrap" @click.stop="">
                <div class="pei-goods" v-for="(item,index) in specs" :key="index">
                    <div class="spec-name">{{item.name}}</div>
                    <div class="item" :class="{active:(item.seledSpec&&item.seledSpec==it)}" v-for="(it,ind) in item.specs" :key="`_${ind}`" @click="modifySpecs('add',it,item)">
                        <div class="info">
                            <div class="item-name">{{it}}</div>
                        </div>
                    </div>
                </div>
                <span class="sure" @click.stop="submitSelSpec">确认</span>
            </div>
        </div>
        <!-- 规格end -->
    </div>
</template>

<script>
import { url } from '@/router/url.js';
export default {
    props: ['openId','storeId'],  
    data(){
        return{
            showDelConfirm:false,
            showPayBox:false, 
            isqrcode:false,
            errMsg:"",
            showPayErr:false,
            // 
            nowReduceItem:null,
            nowSelNeedSpecItem:null,
            nowSelSpec:[],
            specs:[],
            fromSelSpec:false,
            showSelSpec:false,
            //
            nowSelPeiGoodsIds:[],
            peiGoods:[],
            showPeiGoods:false,
            nowSelPeiGoods:[],
            nowSelNeedPeiItem:null,
            goodsData:[{}], // 商品列表
            curIdx:0, // 当前选择商品分类索引
            showCarDetail: false, // 控制显示购物车详情
            showCode: false, // 控制显示二维码
            iScrollBtn: false, // 控制非IOS机型下，滚动条样式
            img: url,

            orderId: '', // 订单id
            choiceArr: [], // 选择商品列表

            totalPrice: {
                count: 0, // 总数量
                total: 0, // 总计金额
                discount: 0, // 优惠金额
                amount: 0, // 最终价格
            },

            animateDom: {}, // 动画dom节点
            carDom: {}, // 购物车dom节点
            winH: 0, // 屏幕高度
            curPaymentId: '', // 当前支付id

            addGoodBtn: true, // 控制添加商品
            reduceGoodBtn: true, // 控制减少商品
            tableNo:'',//桌号
            vipData:[],//会员
            curVipPerson:{},
            upVipBtn:'1',
            vipNum:'',

            goodNumber: '', //数字键盘输入商品数量
            curProductId: '', // 当前点击的商品
            showNumBox: false, // 显示数字键盘
            nowImg:'',
            canClick:true,
            productList:[],
            product:""
        }
    },
    watch:{
        showPeiGoods(val){
            if(!val){
                this.nowSelPeiGoods = [];
                this.nowSelPeiGoodsIds = [];
                this.nowSelNeedPeiItem = null;
            }
        },
         //搜索获取商品
        product ( val ) {
            if ( !(val.replace(/\s/g,'')) ) {
                this.productList = [];
                return;
            }
            this.$http.get('products/search?storeId='+this.storeId+'&q='+encodeURI(val)).then((res)=>{
                this.productList = res.data;
            })
        },
    },
    methods: {
        //搜索并添加商品
        shoiceProduct(item){
            if((item.productSpecs && Array.isArray(item.productSpecs) && item.productSpecs.length) || (item.productSpecSet && Array.isArray(item.productSpecSet) && item.productSpecSet.length)){
                this.productList = [];
                this.product = '';
                if(item.productSpecSet && Array.isArray(item.productSpecSet) && item.productSpecSet.length){
                    item.productSpecs = item.productSpecSet;
                }
                this.beforeSelGoods(item);
                return;
            }
            this.addProduct(item.id, true,null,true,null);
            this.productList = [];
            this.product = '';
        },
        // 
          beforeCloseSpec(){
            this.nowSelNeedSpecItem = null;
            this.nowSelSpec = [];
            this.fromSelSpec = false;
            this.showSelSpec = false;
        },
        modifySpecs(type,it,item){
            item.seledSpec = it;
            console.log(this.specs);
            let nowSelSpec = [];
            if(this.specs && Array.isArray(this.specs) && this.specs.length){
                this.specs.forEach(it=>{
                    if(it.seledSpec){
                        nowSelSpec.push(it.seledSpec);
                    }
                })
            }
            console.log(nowSelSpec)
            this.nowSelSpec = nowSelSpec;
            this.$forceUpdate();
        },
        submitSelSpec(){
            if(!this.nowSelSpec || !this.nowSelSpec.length ){
                this.$message({
                    message: "请选择规格",
                    customClass: 'error'
                });
                return;
            }
            console.log(this.nowSelSpec);
            if(this.nowSelSpec.length!=this.specs.length){
                this.$message({
                    message: "请完整选择规格",
                    customClass: 'error'
                });
                return;
            }
            // 
            this.goodSearch = '';
            if ( this.upBtn ) return;
            if ( this.nowSelNeedSpecItem.id == '0' ) {
                this.showCustomPrice = true;
                this.customPrice = '';
                setTimeout(()=>{
                    $('#customPriceInput').focus();
                })
                return;
            }
            this.fromSelSpec = true;
            this.addProduct( this.nowSelNeedSpecItem.id );
            this.canClick = false;
            setTimeout(()=>{
                this.canClick = true;
            },500);
            // 
        },
        // 
        beforeSelGoods(item){
            console.log(item)
            if(item.stockEnabled&&!item.quantity){
				this.$message({
		        	message: '无货',
		        	customClass: 'error'
		        });
				return;
			}
			if(item.productSpecs && Array.isArray(item.productSpecs) && item.productSpecs.length){
                let resetFlag = true;
                let seledItem = null;
                if(this.choiceArr && Array.isArray(this.choiceArr) && this.choiceArr.length){
                    this.choiceArr.forEach(it=>{
                        if(it.productId == item.id){
                            resetFlag = false;
                            seledItem = it;
                        }
                    })
                }
                if(item.productSpecs && Array.isArray(item.productSpecs)){
                    if(resetFlag){
                        let nowSelSpec = [];
                        item.productSpecs.forEach(it=>{
                            it.seledSpec = it.defaultSpec;
                            nowSelSpec.push(it.defaultSpec);
                        })
                        this.nowSelSpec = nowSelSpec;
                    }else{
                        if(seledItem && seledItem.specs && Array.isArray(seledItem.specs)){
                            item.productSpecs.forEach(it=>{
                                if(it.specs && Array.isArray(it.specs)){
                                    it.specs.forEach(ite=>{
                                        if(seledItem.specs.indexOf(ite)!=-1){
                                            it.seledSpec = ite;
                                        }
                                    })
                                }
                            })
                          this.nowSelSpec = seledItem.specs;
                        }
                    }
                }
                this.specs = item.productSpecs;
                this.nowSelNeedSpecItem = item;
                this.showSelSpec = true;
                return
            }
			this.addProduct( item.id,true,null,false,item);
		},
        // 
        reduceAmountForPei(it){
            if(!this.canClick){
                return;
            }
            this.canClick = false;
            this.$http({
                url:`orders/${this.orderId}/remove/match`,
                method:"POST",
                data:{
                    orderItemId:it.id,
                    productCount:1
                }
            }).then(res=>{
                setTimeout(()=>{
                    this.canClick = true;
                },1000);
                this.$message({
                    message: "操作成功",
                    showClose: true,
                    customClass: 'success'
                });
                //
                let body = res.data;
                this.choiceArr = body.items;
                this.totalPrice = {
                    count: body.count, // 总数量
                    total: body.total, // 总计金额
                    discount: body.discount, // 优惠金额
                    amount: body.amount, // 最终价格
                    removeZero: body.removeZero, // 最终价格
                }
                this.addGoodBtn = true;
                // 
                // this.returnMoney(false);
                return;
            }).catch(err=>{
                setTimeout(()=>{
                    this.canClick = true;
                },1000);
            })
        },
        addAmountForPei(item,it){
            if(!this.canClick){
                return;
            }
            this.canClick = false;
            let data = {
                    orderItemId:item.id,
                    orderId:this.orderId,
                    matchParams:[
                        {
                            masterItemId:it.id,
                            productId:it.productId,
                            productCount:1,
                            amount:(it.salesPrice / it.quantity).toFixed(2),
                        }
                    ]
                }
                this.$http({
                    url:`orders/${this.orderId}/add/match`,
                    method:"POST",
                    data
                }).then(res=>{
                    this.showPeiGoods = false;
                    this.$message({
                        message: "操作成功",
                        showClose: true,
                        customClass: 'success'
                    });
                    //
                    let body = res.data;
                    this.choiceArr = body.items;
                    this.totalPrice = {
                        count: body.count, // 总数量
                        total: body.total, // 总计金额
                        discount: body.discount, // 优惠金额
                        amount: body.amount, // 最终价格
                        removeZero: body.removeZero, // 最终价格
                    }
                    this.addGoodBtn = true;
                    //
                    setTimeout(()=>{
                        this.canClick = true;
                    },1000);
                    // this.returnMoney(false);
                }).catch(err=>{
                    setTimeout(()=>{
                        this.canClick = true;
                    },1000);
                })
        },
        modifyPeiGoods(type,item){
        //    if(this.nowSelPeiGoods!=null && item.productId != this.nowSelPeiGoods.productId){
        //        this.$message({
        //             message: "暂支持添加单个配品",
        //             showClose: true,
        //             customClass: 'error'
        //         });
        //        return;
        //    }
        //     if(type == "add"){
        //         item.selCount++;
        //         this.nowSelPeiGoods = item;
        //     }else{
        //         item.selCount--;
        //         if(item.selCount <= 0){
        //             item.selCount = 0;
        //             this.nowSelPeiGoods = null;
        //             return;
        //         }
        //     }
            if(type == "add"){
                let nowSelPeiGoods = JSON.parse(JSON.stringify(this.nowSelPeiGoods));
                
                let flag = true;
                let index;
                if(nowSelPeiGoods && Array.isArray(nowSelPeiGoods) && nowSelPeiGoods.length){
                    nowSelPeiGoods.forEach((it,ind)=>{
                        if(it.id == item.id){
                            flag = false;
                            index = ind;
                        }
                    })
                }
                if(flag){
                    nowSelPeiGoods.push(item);
                }else{
                    nowSelPeiGoods.splice(index,1);
                }

                let nowSelPeiGoodsIds = [];
                nowSelPeiGoods.forEach(it=>{
                    nowSelPeiGoodsIds.push(it.id);
                });
                this.nowSelPeiGoods = nowSelPeiGoods;
                this.nowSelPeiGoodsIds = nowSelPeiGoodsIds;
            }
        },
        submitSelPei(){
            if(this.peiGoods && Array.isArray(this.peiGoods) && this.peiGoods.length){
                if(!this.canClick){
                    return;
                }
                this.canClick = false;
                let matchParams = [];
                if(this.nowSelPeiGoods && Array.isArray(this.nowSelPeiGoods) && this.nowSelPeiGoods.length){
                    this.nowSelPeiGoods.forEach(it=>{
                        let obj = {
                            masterItemId:"",
                            productId:it.id,
                            productCount:1,
                            amount:it.salesPrice,
                        }
                        matchParams.push(obj);
                    })
                }
                if(!matchParams.length){
                    this.$message({
                        message: "请选择配品",
                        showClose: true,
                        customClass: 'error'
                    });
                    this.canClick = true;
                    return;
                }
                let data = {
                    orderItemId:this.nowSelNeedPeiItem.id,
                    orderId:this.orderId,
                    matchParams
                    // masterItemId:"",
                    // productId:this.nowSelPeiGoods.id,
                    // productCount:this.nowSelPeiGoods.selCount,
                    // amount:Number(this.nowSelPeiGoods.selCount)*Number(this.nowSelPeiGoods.salesPrice),
                }
                this.$http({
                    url:`orders/${this.orderId}/add/match`,
                    method:"POST",
                    data
                }).then(res=>{
                    this.showPeiGoods = false;
                    this.$message({
                        message: "操作成功",
                        showClose: true,
                        customClass: 'success'
                    });
                    //
                    let body = res.data;
                    this.choiceArr = body.items;
                    this.totalPrice = {
                        count: body.count, // 总数量
                        total: body.total, // 总计金额
                        discount: body.discount, // 优惠金额
                        amount: body.amount, // 最终价格
                        removeZero: body.removeZero, // 最终价格
                    }
                    this.addGoodBtn = true;
                    // 
                    setTimeout(()=>{
                        this.canClick = true;
                    },1000);
                    // this.returnMoney(false);
                }).catch(err=>{
                    setTimeout(()=>{
                        this.canClick = true;
                    },1000);
                })
            }
        },
        doShowPeiGoods(item){
            this.nowSelNeedPeiItem = item;
            this.nowSelPeiGoodsIds = [];
            this.nowSelPeiGoods = [];
            if(item.masterItemDtos && Array.isArray(item.masterItemDtos) && item.masterItemDtos.length){
                let nowSelPeiGoodsIds = [];
                let masterItemDtos = JSON.parse(JSON.stringify(item.masterItemDtos));
                let obj = {};
                masterItemDtos.forEach(it=>{
                    obj[it.productId] = it;
                    nowSelPeiGoodsIds.push(it.productId);
                });
                let tempArr = [];
                for(let k in obj){
                    obj[k]["id"] =  obj[k].productId;
                    tempArr.push(obj[k]);
                }
                this.nowSelPeiGoodsIds = nowSelPeiGoodsIds;
                this.nowSelPeiGoods = tempArr;
            }
            this.$http({
                url:"orders/match/product/list",
                method:"POST",
                data:{
                    productId:item.productId
                }
            }).then(res=>{
                if(res.data && Array.isArray(res.data) && res.data.length){
                    res.data.forEach(it=>{
                        it.selCount = 0;
                    })
                    this.peiGoods = res.data;
                    this.showPeiGoods = true;
                }else{
                   this.$message({
                        message: "暂无相关配品，请在后台设置。",
                        customClass: 'error'
                    });
                    return;
                }
            })
        },
        //   显示商品图片信息
        showImg(imgInfo){
            console.log(imgInfo)
            if(imgInfo){
                this.nowImg = imgInfo;
            }
        },
        hideImg(){
            this.nowImg = '';
        },
        openNumberBox: function ( productId ) {
            this.showNumBox = true;
            this.curProductId = productId;
            this.goodNumber = '';
        },
        clickNum: function ( num ) {
            if ( !this.goodNumber && num == '0' ) {
                return;
            }
            if ( this.goodNumber.length >= 4 ) {
                return;
            }
            this.goodNumber += num;
        },
        delNumber: function () {
            this.goodNumber = this.goodNumber.substring(0, this.goodNumber.length-1);
        },
        saveNumber: function () {
            if ( !this.goodNumber ) {
                return;
            }
            this.addProduct(this.curProductId, true, parseInt(this.goodNumber));
            this.showNumBox = false;
        },

        // 收缩展开商品分类
        traggerType: function ( evnet ) {
            if ( $(event.target).parent().css('height') == '50px' ) {
                $(event.target).parent().css('height', 'auto');
            } else {
                $(event.target).parent().css('height', '50px');
            }
        },
        // 点击选好了触发
        goPayType: function () {
            if(this.choiceArr.length){
                // 以下代码不知为什么会要清除订单
                // sessionStorage.removeItem('orderId');
                this.$router.push('waitPay/'+this.orderId);
            }else {
                this.$message({
                    message: '请选择商品',
                    customClass: 'error'
                })
            }
        },
        // 切换商品分类
        changeGoodType: function ( index ) {
            this.curIdx = index;
            let that = this;
            setTimeout(()=>{
                $('.goods_item').css('height','50px');
                $('.goods_item.oneLevel').css('height','auto');
                $('.goods_item:nth-of-type(2)').css('height','auto');
                $('.goods_item .changeNumber .addNumber').bind('moveAnimate', function ( e, curDom ) {
                    that.animateDom.css("left", $(curDom).offset().left + "px");
                    that.animateDom.css("top", $(curDom).offset().top  + "px");
                    that.shoppingCartAnimate();
                })

                Echo.init({
                    offset: 0,//离可视区域多少像素的图片可以被加载
                　　throttle: 0, //图片延时多少毫秒加载
                    scrollDomId: 'right_goods',
                });
            });
        },
        // 获取商品列表
        getGoods(){
            this.$http.get('products?storeId='+ this.storeId).then((res)=>{
                this.goodsData = res.data;
                if(res.data && Array.isArray(res.data) && res.data.length>1){
                    this.curIdx = 1;
                }
                let that = this;
                setTimeout(()=>{
                    $('.goods_item .changeNumber .addNumber').bind('moveAnimate', function ( e, curDom ) {
                        that.animateDom.css("left", $(curDom).offset().left + "px");
                        that.animateDom.css("top", $(curDom).offset().top  + "px");
                        that.shoppingCartAnimate();
                    })

                    Echo.init({
                        offset: 0,//离可视区域多少像素的图片可以被加载
                    　　throttle: 0, //图片延时多少毫秒加载
                        scrollDomId: 'right_goods',
                    });
                });
            })
        },
        // 购物车动画
        shoppingCartAnimate(){
            var flyElm = this.animateDom.clone();
            $('.takeOrder').append(flyElm);
            flyElm.css({
                'zIndex': 99,
                'opacity': 1,
                'top': this.animateDom.offset().top +'px',
                'left': this.animateDom.offset().left +'px',
            });
            flyElm.animate({
                top: this.carDom.offset().top,
                left: this.carDom.offset().left,
                width: 10,
                height: 10
            }, 'slow', function() {
                flyElm.remove();
            });
        },
        // 添加商品
        addProduct: function ( productId, btn, num,item ) {
            if ( productId == '0' && !num) {
                return;
            }
            if ( !this.addGoodBtn ) {
                return;
            }
            this.addGoodBtn = false;

            let data = {
                "productId": productId,
                "productCount": 1,
                specs:this.fromSelSpec?this.nowSelSpec:undefined
            }
            if(item && Array.isArray(item.specs) && item.specs.length){
                data["specs"] = item.specs;
            }
            if ( productId == '0' ) {
                data = {
                    "productId": productId,
                    "productCount": 1,
                    "amount": num
                }
            }
            if(sessionStorage.getItem('orderId')){
                this.orderId = sessionStorage.getItem('orderId');
            }else{

                // test

                // this.orderId = this.$uuid.create(1).hex;
                // sessionStorage.setItem('orderId', this.orderId);
                // this.$http.put('orders/'+ this.orderId+'?storeId='+this.storeId+'&openId='+this.openId).then((res)=>{
                //     console.log(res);
                //     return;
                // }).catch(()=>{
                //     // this.createOrder();
                //     console.log('err');
                //     return;
                // })

                // test

                // add
                // this.$http.post('orders/' + this.orderId + '/add', data).then((res)=>{
                //     if ( btn ) {
                //         $('#'+productId).trigger('moveAnimate', $('#'+productId));
                //     }
                //     let body = res.data;
                //     this.choiceArr = body.items;
                //     this.totalPrice = {
                //         count: body.count, // 总数量
                //         total: body.total, // 总计金额
                //         discount: body.discount, // 优惠金额
                //         amount: body.amount, // 最终价格
                //     }
                //     this.addGoodBtn = true;
                // }).catch((err)=>{
                //     this.addGoodBtn = true;
                // })
                // add




                //没有就新建id
                let url='?createTime='+new Date().getTime()+'&storeId='+this.storeId+'&openId='+this.openId;
                this.$http.put('/create-orders'+url).then((res)=>{
                    console.log(res);
                    sessionStorage.setItem('orderId',res.data.id);
                    this.orderId = res.data.id;
                    this.$http.post('orders/' + this.orderId + '/add', data).then((res)=>{
                        // 
                        try {
							let pId = `${this.nowSelSpec}_&_${productId}`;
							if(res.data.items && Array.isArray(res.data.items) && res.data.items.length){
								res.data.items.forEach(it=>{
									if((`${it.specs}_&_${it.productId}` == pId && it.matchEnabled) || (it.productId==productId && it.matchEnabled)){
										this.doShowPeiGoods(it);
									}
								})
							}
						} catch (error) {
							console.log(error);
						}
                        // 
                        this.fromSelSpec = false;
                        this.showSelSpec = false;
                        if ( btn ) {
                            $('#'+productId).trigger('moveAnimate', $('#'+productId));
                        }
                        let body = res.data;
                        this.choiceArr = body.items;
                        this.totalPrice = {
                            count: body.count, // 总数量
                            total: body.total, // 总计金额
                            discount: body.discount, // 优惠金额
                            amount: body.amount, // 最终价格
                        }
                        this.addGoodBtn = true;
                    }).catch((err)=>{
                        this.fromSelSpec = false;
                        this.showSelSpec = false;
                        this.addGoodBtn = true;
                    })
                })
                return;
            }
            this.$http.post('orders/' + this.orderId + '/add', data).then((res)=>{
                // 
                try {
                    let pId = `${this.nowSelSpec}_&_${productId}`;
                    if(res.data.items && Array.isArray(res.data.items) && res.data.items.length){
                        res.data.items.forEach(it=>{
                            if((`${it.specs}_&_${it.productId}` == pId && it.matchEnabled) || (it.productId==productId && it.matchEnabled)){
                                this.doShowPeiGoods(it);
                            }
                        })
                    }
                } catch (error) {
                    console.log(error);
                }
                // 
                this.fromSelSpec = false;
                this.showSelSpec = false;
                if ( btn ) {
                    $('#'+productId).trigger('moveAnimate', $('#'+productId));
                }
                let body = res.data;
                this.choiceArr = body.items;
                this.totalPrice = {
                    count: body.count, // 总数量
                    total: body.total, // 总计金额
                    discount: body.discount, // 优惠金额
                    amount: body.amount, // 最终价格
                }
                this.addGoodBtn = true;
            }).catch((err)=>{
                this.fromSelSpec = false;
                this.showSelSpec = false;
                this.addGoodBtn = true;
            })
        },
        // 减少商品
        reduceProduct: function ( productId ,item) {
            if ( !this.reduceGoodBtn ) {
                return;
            }
            this.reduceGoodBtn = false;
            let data = {
                "productId": productId,
                "productCount": 1,
                specs:(item.specs&&Array.isArray(item.specs)&&item.specs.length)?item.specs:undefined
            };
            this.$http.post('orders/' + this.orderId + '/remove', data).then((res)=>{
                let body = res.data;
                if(body==''){
                    //订单已经删除
                    sessionStorage.removeItem('orderId');
                    this.choiceArr = [];
                    this.showCarDetail = false;
                    this.showPayBox = false;
                    
                    this.totalPrice = {
                        count: 0, // 总数量
                        total: 0, // 总计金额
                        discount: 0, // 优惠金额
                        amount: 0, // 最终价格
                    };
                    this.reduceGoodBtn = true;
                    return;
                }
                this.choiceArr = body.items;
                if ( this.choiceArr.length <= 0 ) {
                    this.showCarDetail = false;
                }
                this.totalPrice = {
                    count: body.count, // 总数量
                    total: body.total, // 总计金额
                    discount: body.discount, // 优惠金额
                    amount: body.amount, // 最终价格
                }
                this.reduceGoodBtn = true;
            }).catch(()=>{
                this.reduceGoodBtn = true;
            })
        },
        // 改变动画位置
        changeAnimate: function ( e ) {
            this.animateDom.css("left", e.screenX + "px");
            this.animateDom.css("top", e.screenY + "px");
        },

        delOrder: function () {
            this.$http.delete('orders/'+ this.orderId).then((res)=>{
                console.log(res);
            })
        },

        // 生成订单
        createOrder: function () {
            this.orderId = this.$uuid.create(1).hex;
            sessionStorage.setItem('orderId', this.orderId);
            this.$http.put('orders/'+ this.orderId+'?storeId='+this.storeId+'&openId='+this.openId).then((res)=>{

            }).catch(()=>{
                // this.createOrder();
            })
        }
    },
    created: function () {
        
        m$.setTitle('点单');
        this.getGoods();
        // 判断是否有缓存订单
        if ( sessionStorage.getItem('orderId') ) {
            this.orderId = sessionStorage.getItem('orderId');
            this.$http.get('orders/' + this.orderId).then((res)=>{
                let body = res.data;
                this.choiceArr = body.items;
                this.totalPrice = {
                    count: body.count, // 总数量
                    total: body.total, // 总计金额
                    discount: body.discount, // 优惠金额
                    amount: body.amount, // 最终价格
                }
            });
        } else {
            // 生成订单
            // this.createOrder();
        }
    },
    mounted: function () {
        this.$createScroll('right_goods');
        this.$createScroll('left_bar');
        this.$createScroll('carGoodsBox');

        this.animateDom = $('.goodAnimate');
        this.carDom = $('.shopCar .carImg');
        this.winH = $(window).height();
    },
}
</script>
<style lang="scss" scoped>
    @import "../../static/css/common.scss";
    @import "takeOrder";
</style>
